<template>
  <el-dialog
    :model-value="permissionVisible"
    title="编辑权限"
    width="40%"
    @close="handleClose"
  >
    <!--
      :default-expanded-keys="[2, 3]"
      :default-checked-keys="[5]"
     -->
    <el-tree
      :data="permissions"
      show-checkbox
      node-key="id"
      :props="defaultProps"
      :default-checked-keys="form.permissionIds"
      @check="handleCurrentChecked"
      ref="tree"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineEmits, defineProps, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { savePermission } from '../../../api/role'

const permissions = ref([])
const form = ref({
  roleId: 0,
  permissionIds: []
})

const props = defineProps({
  permissionValue: {
    type: Object,
    default: () => {}
  },
  permissionIdsValue: {
    type: Object,
    default: () => {}
  },
  roleIdValue: {
    type: Object,
    default: () => {}
  }
})
watch(
  () => props,
  () => {
    // console.log(props.dialogRowValue)
    permissions.value = props.permissionValue
    form.value.permissionIds = props.permissionIdsValue
    form.value.roleId = props.roleIdValue
  },
  { deep: true, immediate: true }
)

const emits = defineEmits(['update:modelValue'])
const defaultProps = {
  children: 'children',
  label: 'label'
}

function handleCurrentChecked(nodeObj, selectedObj) {
  form.value.permissionIds = selectedObj.checkedKeys
}

// 关闭
function handleClose() {
  emits('update:modelValue', false)
}
// 确认
async function handleConfirm() {
    const resp = await savePermission(form.value)
    if (resp.data.code === '200') {
      ElMessage({
        message: '更新成功',
        type: 'success'
      })
    }
    handleClose()
}
</script>

<style lang="scss" scoped>
::v-deep .el-input__prefix-inner {
  align-items: center;
}
</style>
